<?php

namespace App\Services\Admin;

use App\Models\Attribute;
use App\Models\AttributeProperty;
use App\Models\Property;

class PropertyService
{
    public function formatInput($inputArr)
    {
        $data = array();
        foreach($inputArr as $k=>$arr){
            $exp = explode(',',$arr);
            $data['id'][] = $exp[0];
            $data['txt'][] = $exp[1];
        }
        return $data;
    }

    // 更新中间属性
    public function updateAttributeMid($data,$id,$type)
    {
        if(count($data)){
            foreach ($data as $d){
                $attr['property_id'] = $id;
                $attr['attribute_id'] = $d;
                $attr['type'] = $type;
                AttributeProperty::create($attr);
            }
        }
    }

    // 删除中间属性表数据
    public function deleteAttributeMid($id,$type)
    {
        AttributeProperty::where('property_id',$id)->where('type',$type)->delete();
    }

    // 获取省份
    public function getProvince()
    {
        return Attribute::where('parent_id',1)->get();
    }

    public function getPropertyById($id)
    {
        return Property::findOrFail($id);
    }

    public function getAllProperty($title,$limit=30)
    {
        $model = Property::query();
        if ($title){
            $model = $model->where('title','like','%'.$title.'%');
        }
        $res = $model->orderBy('created_at','desc')->paginate($limit)->toArray();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }

}